package com.fx.server.server.impl;

import com.fx.common.domain.ImageCode;
import com.fx.server.server.CacheImageCodeService;
import com.wf.captcha.ArithmeticCaptcha;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

@Service
public class MemoryCacheImageCodeService implements CacheImageCodeService {

    private final static ConcurrentHashMap<String,String> cache = new ConcurrentHashMap();

    @Override
    public ImageCode cacheImageCode() {

        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111,36);
        captcha.setLen(2);
        String code = captcha.text();
        String key = RandomStringUtils.random(16);
        cache.put(key,code);
        ImageCode imageCode = new ImageCode(captcha.toBase64(""),key);
        return imageCode;
    }

    @Override
    public String imageCode(String key) {
        return cache.get(key);
    }
}
